package com.gamutsoft.amb.base.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.gamutsoft.amb.common.constants.Constants;
import com.gamutsoft.amb.common.util.PageUtil;
import com.gamutsoft.amb.user.model.SystemUser;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

/**
 * @author lieping zhu
 * 
 */
public class BaseAction extends ActionSupport implements Preparable {

	protected transient final Log log = LogFactory.getLog(getClass());

	private static final long serialVersionUID = 1L;

	public static final String CANCEL = "cancel";
	public static final String SUCCESS = "success";
	public static final String INPUT = "input";
	public static final String ERROR = "error";
	public static final String SYSERROR = "syserror";
	public static final String LOGIN = "login";
	public static final String SYSUCCESS = "sysuccess";
	public static final String SYSINFO = "sysinfo";
	//分页
	private PageUtil pageUtil = new PageUtil();

	public void prepare() throws Exception {

	}
	
	
	
	public SystemUser getSystemUser(){
		SystemUser staff =(SystemUser) this.getSession().getAttribute(Constants.SESSION_USER);
		if(staff == null) {
			log.error("There is no user login!");
		}
		return staff;
	}

	/**
	 * 取得当前request
	 * 
	 * @return
	 */
	protected HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	/**
	 * 取得session
	 * 
	 * @return
	 */
	protected HttpSession getSession() {
		return getRequest().getSession();
	}

	/**
	 * 取得response
	 * 
	 * @return
	 */
	protected HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	/**
	 * 从spring容器中取得bean
	 * 
	 * @param name
	 * @return
	 */
	public Object getBean(String name) {
		ApplicationContext ctx = WebApplicationContextUtils
				.getRequiredWebApplicationContext(this.getRequest()
						.getSession().getServletContext());
		return ctx.getBean(name);
	}

	/**
	 * 向reponse中写入str
	 * 
	 * @param str
	 * @throws IOException
	 */
	protected void writeString(String str) throws IOException {
		HttpServletResponse response = getResponse();
		response.setContentType("text/xml; charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.write(str);
		out.close();
	}

	public PageUtil getPageUtil() {
		return pageUtil;
	}

	public void setPageUtil(PageUtil pageUtil) {
		this.pageUtil = pageUtil;
	}

}
